import torch
import cv2
import os
import uuid

def worker_process_video(video_path):
    output_dir = "./output"
    os.makedirs(output_dir, exist_ok=True)

    #生成唯一的输出文件名
    output_filename = f"processed_video_{uuid.uuid4().hex}.mp4"
    output_path = os.path.join(output_dir, output_filename)

    #加载模型
    model = torch.hub.load('./yolov5', 'custom', path='./models/yolov5s.pt', source='local')

    # 创建视频捕获对象
    cap = cv2.VideoCapture(video_path)
    #获取视频的属性
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)

    #创建视频写入对象 （可选，主要用于我们后期用于保存处理后的数据）
    output_path = "output_video.mp4"
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_path,fourcc,fps,(frame_width,frame_height))

    while cap.isOpened():
        ret,frame = cap.read()
        if not ret:
            break
        #对每一帧进行目标检测
        results = model(frame)

        #渲染结果（在帧上绘制边界框等）
        rendered_frame = results.render()[0]

        #显示处理好的帧
        cv2.imshow('YOLOv5 Detection',rendered_frame)

        #保存处理后的帧到输出视频（可选）
        out.write(rendered_frame)

        # 按 'q'退出程序
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    #释放资源
    cap.release()
    out.release()
    cv2.destroyAllWindows()